package com.sinogrand.elevator.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.zIndex
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import com.sinogrand.elevator.data.models.ProjectDetailData
import com.sinogrand.elevator.network.NetworkClient
import com.google.gson.JsonObject

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProjectOverviewTab(
    project: ProjectItem
) {
    var isRefreshing by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullToRefreshState()
    val context = LocalContext.current
    val apiService = remember { NetworkClient.getApiService(context) }
    
    // 获取项目详情数据
    var projectDetailData by remember { mutableStateOf<ProjectDetailData?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    // 加载项目详情的函数
    suspend fun loadProjectDetail() {
        try {
            isLoading = true
            errorMessage = null
            
            // 构建请求参数
            val request = JsonObject().apply {
                addProperty("id", project.id.toInt())
            }
            
            // 调用API获取数据
            val apiResponse = apiService.getProjectInfo(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                projectDetailData = apiResponse.data
            } else {
                // API失败时显示错误信息
                projectDetailData = null
                errorMessage = "API请求失败: ${apiResponse.msg}"
            }
        } catch (e: Exception) {
            // 异常时显示错误信息
            projectDetailData = null
            errorMessage = "网络请求异常: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    // 初始化数据
    LaunchedEffect(project.id) {
        loadProjectDetail()
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            loadProjectDetail()
            isRefreshing = false
            pullRefreshState.endRefresh()
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
            contentPadding = PaddingValues(
                top = 8.dp,
                bottom = 16.dp
            )
        ) {
            // 加载状态 - 只在没有数据时显示
            if (isLoading && projectDetailData == null) {
                item {
                    LoadingIndicator()
                }
            }
            
            // 错误信息
            errorMessage?.let { message ->
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = Color(0xFFFEF2F2)
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Text(
                            text = message,
                            fontSize = 14.sp,
                            color = Color(0xFFDC2626),
                            modifier = Modifier.padding(16.dp)
                        )
                    }
                }
            }
            
            // 项目详情信息卡片
            projectDetailData?.let { data ->
                item {
                    ProjectDetailInfoCard(projectDetails = data.info)
                }
            }
            
            // 加载失败UI - 当没有数据且不是加载状态时显示
            if (!isLoading && projectDetailData == null && errorMessage == null) {
                item {
                    LoadFailedUI()
                }
            }
        }
        
        // 下拉刷新容器 - 只在需要时显示
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f) // 确保在列表内容之上
            )
        }
    }
}

@Composable
fun ProjectDetailInfoCard(projectDetails: com.sinogrand.elevator.data.models.ProjectInfo) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "项目信息",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF1F2937)
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 显示所有详情字段
            projectDetails.details.forEach { field ->
                if (field.visible) {
                    val fieldValue = runCatching {
                        field.values.firstOrNull() ?: ""
                    }.getOrElse { 
                        ""
                    }
                    ProjectDetailInfoRow(
                        label = field.name,
                        value = fieldValue
                    )
                }
            }
        }
    }
}

@Composable
fun ProjectDetailInfoRow(
    label: String,
    value: String
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 14.sp,
            color = Color(0xFF6B7280),
            modifier = Modifier.weight(1f)
        )
        
        Text(
            text = value,
            fontSize = 14.sp,
            color = Color(0xFF1F2937),
            modifier = Modifier.weight(1f),
            textAlign = androidx.compose.ui.text.style.TextAlign.End
        )
    }
    
    // 分隔线
    HorizontalDivider(
        color = Color(0xFFE5E7EB),
        thickness = 0.5.dp,
        modifier = Modifier.padding(vertical = 4.dp)
    )
}



@Composable
fun LoadingIndicator() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        contentAlignment = Alignment.Center
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            CircularProgressIndicator(
                modifier = Modifier.size(20.dp),
                strokeWidth = 2.dp,
                color = Color(0xFF3B82F6)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "加载中...",
                fontSize = 14.sp,
                color = Color(0xFF6B7280)
            )
        }
    }
}

@Composable
fun NoMoreDataIndicator() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "没有更多数据了",
            fontSize = 14.sp,
            color = Color(0xFF6B7280)
        )
    }
}

@Composable
fun LoadFailedUI() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFF9FAFB)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(32.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = Icons.Filled.Warning,
                contentDescription = null,
                modifier = Modifier.size(48.dp),
                tint = Color(0xFF6B7280).copy(alpha = 0.6f)
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            Text(
                text = "加载失败",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF374151)
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = "无法获取项目详情，请下拉刷新重试",
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                textAlign = androidx.compose.ui.text.style.TextAlign.Center
            )
        }
    }
}

